<?php

namespace App\WechatHandlers;

use App\Models\WechatGroup;
use App\Models\WechatMenu;
use App\Models\WechatMessage;
use EasyWeChat\Kernel\Contracts\EventHandlerInterface;

/**
 * Class EventHandler
 * @package App\WechatHandler
 * 事件处理器
 */
class EventHandler implements EventHandlerInterface
{
    /**
     * @param null $message
     * @return string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function handle($message = null)
    {
        //若存在规则并且检测到事件类型为被关注
        if ($message['Event'] == 'subscribe') {
//            $openid = $message['FromUserName'];
//            $userModel = User::where("official_openid", $openid)->first();
//            if(!$userModel){
//                $userMessage = Facade::officialAccount()->user->get($openid);
//                if(!array_get($userMessage,'errcode')){
//                    $user= new User();
//                    $user->official_openid = $userMessage['openid'];
//                    $user->name = $userMessage['nickname'];
//                    $user->is_new = 1;
//                    if(array_get($userMessage,"unionid")){
//                        $user->unionid = $userMessage['unionid'];
//                    }
//                    $user->save();
//                }
//            }
            // 被关注消息回复
            $subscribeData = WechatMessage::orderBy('sort', 'asc')
                ->isEnable()->responseTypeSubscribe()->first();
            if ($subscribeData) {
                // 给该规则使用次数+1
                $subscribeData->increment('count');
                // 再分别按照消息回复方式进行组装数据
                return $subscribeData->getResponse();
            }
        }
        // click
        if ($message['Event'] == 'CLICK') {
            $groupId = WechatGroup::isEnable()->first()->id;
            $textData = WechatMenu::orderBy('sort', 'asc')->isEnable()->where('type', 'click')->where('group_id', $groupId)->get()->toArray();
            foreach ($textData as $v) {
                if ($message['EventKey'] == $v['key']) {
                    return $v['text'];
                }
            }
        }
        return '';
    }
}
